package com.java.common;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 用于字符和时间类型之间的转换;
 *
 */
public class DateUtil {
	
	final static Logger logger = LoggerFactory.getLogger(DateUtil.class);
	
    public final static String defaultDatePattern = "yyyy-MM-dd";
    public final static String defaultTimePattern = "HH:mm:ss.S";    
    public final static String dafaultDateTimePattern = defaultDatePattern + " " + defaultTimePattern;    

    /**
     * 获取当前年份
     * return - 2009
     */
    public static Integer getCurYear(){
    	Calendar ca = Calendar.getInstance();
        ca.setTime(new java.util.Date());        
    	return ca.get(Calendar.YEAR); 
    }
    /**
     * 获取当前月份
     * return - 12
     */
    public static Integer getCurMonth(){
    	Calendar ca = Calendar.getInstance();
        ca.setTime(new java.util.Date());        
        //+1才是当前月
    	return ca.get(Calendar.MONTH)+1; 
    }
       
    /**
     * 根据传入的格式符将字符串转换为日期时间类型；
     * 
     */
    public static final Date getDateTimefromString(String aMask, String strDate)
      throws ParseException {
        SimpleDateFormat df = null;
        Date date = null;
        df = new SimpleDateFormat(aMask);

        try {
            date = df.parse(strDate);
        } catch (ParseException pe) {
            logger.error(pe.getMessage(),pe);
        }

        return (date);
    }
    
    /**
     * 利用缺省的时间日期格式符将字符串转换为日期时间类型；
     * 2009-10-07
     */
    public static final Date getDatefromStringByDefaultPatten(String strDate)
      throws ParseException {
        return getDateTimefromString(defaultDatePattern,strDate);
    }
    /**
     * 利用自定义时间日期格式获取日期；
     * 2009-10-07
     */
  public static final Date getDate(String aMask) {
    	SimpleDateFormat df = new SimpleDateFormat(aMask);
    	Date date = null;
    	try {
    		date = df.parse(df.format(new Date()));    		
    	} catch (ParseException pe) {
    		logger.error(pe.getMessage(),pe);
    	}
   return (date);
    }
  /**
   * 得到几天前的时间
   * @param date
   * @param day
   * @return
   */
  public static Date getDateBefore(Date date,int day){
   Calendar now =Calendar.getInstance();
   now.setTime(date);
   now.set(Calendar.DATE,now.get(Calendar.DATE)-day);
   return now.getTime();
  }
  
  /**
   * 得到几天后的时间
   * @param date
   * @param day
   * @return
   */
  public static Date getDateAfter(Date date,int day){
   Calendar now =Calendar.getInstance();
   now.setTime(date);
   now.set(Calendar.DATE,now.get(Calendar.DATE)+day);
   return now.getTime();
  }
  
  /**
   * 得到几个月前的时间
   * @param date
   * @param day
   * @return
   */
  public static Date getDateBeforeMonths(Date date,int month){
	   GregorianCalendar calendar = new GregorianCalendar();
	   calendar.setTime(date);
	   calendar.add(Calendar.MONTH, 0-month);
	   return calendar.getTime();
  }
 
  /**
   * 得到几个月后的时间
   * @param date
   * @param day
   * @return
   */
  public static Date getDateAfterMonths(Date date,int month){
	   GregorianCalendar calendar = new GregorianCalendar();
	   calendar.setTime(date);
	   calendar.add(Calendar.MONTH, month);
	   return calendar.getTime();
  }
  

    /**
     * 利用缺省的日期格式符将字符串转换为时间类型；
     * 17:27:31.122
     */
    public static final Date getTimefromStringByDefaultPatten(String strDate)
      throws ParseException {
        return getDateTimefromString(defaultTimePattern,strDate);
    }
 
    /**
     * 利用缺省的日期和时间格式符将字符串转换为时间类型；
     * 2009-10-07 17:20:55.483
     */
    public static final Date getDateTimefromStringByDefaultPatten(String strDate)
      throws ParseException {
        return getDateTimefromString(dafaultDateTimePattern,strDate);
    }
    
    /**
     * 根据传入的格式符将时间类型转换为字符串
     * 
     */
    public static final String getDateTimeFormString(String aMask, Date aDate) {
        SimpleDateFormat df = null;
        String returnValue = "";

        if (aDate == null) {
           return null;
        } else {
            df = new SimpleDateFormat(aMask);
            returnValue = df.format(aDate);
        }

        return (returnValue);
    }
    /**
     * 计算两个时间的间隔
     * @param startTime String 起始时间
     * @param endTime String 结束时间
     * @return interval String *天*时*分*秒
     * @throws ParseException 
     */
  public static final String getTimeInterval(String startTime,String endTime) {
    	String interval = "";
    	long between = 0l;
    	try {
			Date begin = getDateTimefromString("yyyy-MM-dd HH:mm:ss",startTime);
			Date end = getDateTimefromString("yyyy-MM-dd HH:mm:ss",endTime);
			if(begin.getTime()>end.getTime()){
				between=(begin.getTime()-end.getTime())/1000;//除以1000是为了转换成秒
			}else{
				between=(end.getTime()-begin.getTime())/1000;//除以1000是为了转换成秒
			}
			long day=between/(24*3600);
			long hour=between%(24*3600)/3600;
			long minute=between%3600/60;
			long second=between%60;
			if(day>0){
	    		interval = day+"天";
	    	}
			if(hour>0){
	    		interval = interval + hour +"小时";
	    	}
			if(minute>0){
	    		interval = interval + minute +"分";
	    	}
			if(second>0){
	    		interval = interval + second +"秒";
	    	}    	
		} catch (ParseException e) {
			logger.error(e.getMessage(),e);
		}
   return interval;
    }
    /**
     * 计算两个时间的间隔
     * @param startTime String 起始时间
     * @param endTime String 结束时间
     * @return interval String *天*时*分*秒
     * @throws ParseException 
     */
    public static final String getTimeInterval(Date startTime,Date endTime) throws ParseException{
    	String interval = "";
    	
    	long between=0l;
    	if(startTime.getTime()>endTime.getTime()){
    		between = (startTime.getTime()-endTime.getTime())/1000;//除以1000是为了转换成秒
    	}else{
    		between = (endTime.getTime()-startTime.getTime())/1000;//除以1000是为了转换成秒
    	    }
    	long day=between/(24*3600);
    	long hour=between%(24*3600)/3600;
    	long minute=between%3600/60;
    	long second=between%60/60;
    	if(day>0){
    		interval = day+"天";
    	}
    	if(hour>0){
    		interval = interval + hour +"小时";
    	}
    	if(minute>0){
    		interval = interval + minute +"分";
    	}
    	if(second>0){
    		interval = interval + second +"秒";
    	}    	
    	return interval;
    }
    /**
     *   计算任意两个时间的间隔天数
     * @param Calendar start 
     * @param Calendar end
     * @return int start在end之前返回n，start在end之后返回-n
     */
    public static final int getIntervalDays(Calendar start,Calendar end){
//    	if(start.after(end)){
//    		Calendar calendar = start;
//    		start = end;
//    		end = calendar;
//    	}
    	long s1 = start.getTimeInMillis();
    	long s2 = end.getTimeInMillis();
    	long s3 = s2 - s1;
    	return (int)(s3/(1000*60*60*24));
    }
    /**
     * 计算任意两个时间的间隔天数
     * @param Date start
     * @param Date end
     * @return int n,start在end之前返回n，start在end之后返回-n
     */
  public static final int getIntervalDays(Date start,Date end) {
//	  if(start.after(end)){
//    		Date date = start;
//    		start = end;
//    		end = date;
//    	}
   long s1 = start.getTime();
   long s2 = end.getTime();
   long s3 = s2 - s1;
   return (int)(s3/(1000*60*60*24));
    }
    /**
     * 计算两个日期的月份差，不足一月算一月
     */
    public static final int getMonthsBetween(Date date1,Date date2) {
    	int between = 0;
    	if(date1 == null || date2 == null){
    		return 0;
    	}
    	try{
    		Calendar a1 = Calendar.getInstance();
    		Calendar a2 = Calendar.getInstance();
    		if(date1.after(date2)){
    			a1.setTime(date2);
    			a2.setTime(date1);
    		}else{
    			a1.setTime(date1);
    			a2.setTime(date2);
    		}    		
    		int a3 = (a2.get(Calendar.YEAR) - a1.get(Calendar.YEAR));    		
    		int b1 = a1.get(Calendar.MONTH)+1;
    		int b2 = a2.get(Calendar.MONTH)+1;
    		int c1 = a1.get(Calendar.DAY_OF_MONTH);
    		int c2 = a2.get(Calendar.DAY_OF_MONTH);
    		between = a3 *12 + (b2-b1) +((c2-c1)>0?1:0);
    	}catch (Exception e) {
    		logger.error(e.getMessage(),e);
		}
    	return between;
    }
    /**
     * 计算两个日期的月份差，不足一月算一月
     */
    public static final int getMonthsBetween(String date1,String date2) {
    	int between = 0;
    	SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
    	try{
    		Calendar a1 = Calendar.getInstance();
    		Calendar a2 = Calendar.getInstance();
    		//第一个日期在第二个日期之后
    		if(format.parse(date1).after(format.parse(date2))){
    			a1.setTime(format.parse(date2));
    			a2.setTime(format.parse(date1));    			
    		}else{
    			a1.setTime(format.parse(date1));
    			a2.setTime(format.parse(date2));
    		}
    		int a3 = (a2.get(Calendar.YEAR) - a1.get(Calendar.YEAR));    		
    		int b1 = a1.get(Calendar.MONTH)+1;
    		int b2 = a2.get(Calendar.MONTH)+1;
    		int c1 = a1.get(Calendar.DAY_OF_MONTH);
    		int c2 = a2.get(Calendar.DAY_OF_MONTH);
    		between = a3 *12 + (b2-b1) +((c2-c1)>0?1:0);    		
    	}catch (Exception e) {
    		logger.error(e.getMessage(),e);
		}
    	return between;
    }
    /**
     * 根据传入的格式符将时间类型转换为字符串
     * aMask : yyyy-MM-dd HH:mm:ss
     *  
     */
    public static final String getCurrentTimeMillisFormString(String aMask,Long aTime) {
        SimpleDateFormat df = null;
        String returnValue = "";
        if (aMask == null) {
        	df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        } else {
            df = new SimpleDateFormat(aMask);            
        }
        if(aTime == null) {
        	returnValue = df.format(System.currentTimeMillis());
        }else{
        	returnValue = df.format(aTime);
        }
        return returnValue;        
    }
    /**
     * 根据缺省的日期格式符将时间类型转换为字符串
     */
    public static final String getDateStringByDefaultPatten(Date aDate) {
        return getDateTimeFormString(defaultDatePattern, aDate);
    }


    /**
     * 根据缺省的时间格式符将时间类型转换为字符串
     */
    public static final String getTimeStringByDefaultPatten(Date aDate) {
        return getDateTimeFormString(defaultTimePattern, aDate);
    }   
    
    /**
     * 根据缺省的日期日期格式符将时间类型转换为字符串
     */
    public static final String getDateTimeStringByDefaultPatten(Date aDate) {
        return getDateTimeFormString(dafaultDateTimePattern, aDate);
    }
    /**
     * 获取每个月第一个星期一的日期
     */
    public static final String getDateTimeStringByFirstWeekOfMonth(Date aDate) {
    	GregorianCalendar cal = new GregorianCalendar();
    	cal.setTime(aDate);
    	cal.setFirstDayOfWeek(GregorianCalendar.MONDAY);   // 设置一个星期的第一天为星期1，默认是星期日
    	cal.set(GregorianCalendar.DAY_OF_WEEK,GregorianCalendar.MONDAY);
    	return getDateTimeFormString(defaultDatePattern, cal.getTime());
    }
    /**
     * 获取每个月第一个星期一的日期
     */
    public static final Date getDateTimeByFirstWeekOfMonth(Date aDate) {
    	GregorianCalendar cal = new GregorianCalendar();
    	cal.setTime(aDate);
    	cal.setFirstDayOfWeek(GregorianCalendar.MONDAY);   // 设置一个星期的第一天为星期1，默认是星期日
    	cal.set(GregorianCalendar.DAY_OF_WEEK,GregorianCalendar.MONDAY);
    	return cal.getTime();
    }
    /**
     * 获取每个月的第一天日期
     */
    public static final String getDateTimeByFirstDayMonth(Date aDate) {
    	GregorianCalendar cal = new GregorianCalendar();
    	cal.setTime(aDate);
    	cal.setFirstDayOfWeek(GregorianCalendar.MONDAY);   // 设置一个星期的第一天为星期1，默认是星期日
    	cal.set(GregorianCalendar.DAY_OF_MONTH,1); 
    	return getDateTimeFormString(defaultDatePattern, cal.getTime());
    }
    /**
     * 获取每个月的第一天日期
     */
    public static final Date getDateByFirstDayMonth(Date aDate) {
    	GregorianCalendar cal = new GregorianCalendar();
    	cal.setTime(aDate);
    	cal.setFirstDayOfWeek(GregorianCalendar.MONDAY);   // 设置一个星期的第一天为星期1，默认是星期日
    	cal.set(GregorianCalendar.DAY_OF_MONTH,1); 
    	return cal.getTime();
    }    
    
}
